package com.xn.app.muying;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jumper.chart.ADFetalHeartChart;
import com.jumper.chart.FHRAndTocoChartLineView;
import com.jumper.data.FHRInfo;
import com.jumper.fetalheart.ADFetalHeart;
import com.jumper.fetalheart.ConnectCallback;
import com.jumper.fetalheart.FinishCallback;
import com.jumper.fetalheart.Mode;
import com.jumper.help.Mp3RecordTimeCreater;
import com.jumper.help.TimeScheduleCallBack;
import com.xn.app.muying.bean.XinLv;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.DateDialog;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

public class RecordingActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = this.getClass().getSimpleName();
    private static final String fileFolderPath = Environment.getExternalStorageDirectory()
            + "/ceshi";
    private TextView tvConnectedState;
    private TextView tvTime;
    private Button start, stop, shu, qie_huan;
    boolean isstart = false;
    ADFetalHeartChart mAdFetalHeartChart;
    FHRAndTocoChartLineView chartView;
    private ADFetalHeart mADFetalHeart;
    //一个时间模拟处理类
    private Mp3RecordTimeCreater mp3RecordTimeCreater;
    private int moshi = 0;
    RelativeLayout td_0;
    TextView tx_1, tx_2, td_4;
    private int taidong = 0;
    ArrayList<Integer> xinlv = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recording);
        // 得到前面已经初始化的单例。
        // 由于是在前一个界面，初始化，这里就不必要做清理工作。
        mADFetalHeart = ADFetalHeart.getInstance(this);
        // 时间定时器，每0.5秒获取一次数据
        mp3RecordTimeCreater = new Mp3RecordTimeCreater();
        mp3RecordTimeCreater.setTimeScheduleCallBack(new TimeScheduleCallBack() {
            @Override
            public void run() {
                // 判断记录是否已经开始
                // 如果已经开始，就开始更新时间
                if (mADFetalHeart.IsRecording()) {
                    mp3RecordTimeCreater.upDataTimeWithFlag();
                }
                //更新主线程
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        long startTime = System.currentTimeMillis();
                        // 获取胎心设备的数据
                        FHRInfo info = mADFetalHeart.getFHRInfo();
                        if (info == null) return;
                        if (isstart) {
                            tvConnectedState.setText(info.getFhr() + "");
                        } else {
                            tvConnectedState.setText("----");
                        }
                        // 开始记录了，才开始描制胎心曲线
                        if (mADFetalHeart.IsRecording()) {
                            // 胎心
                            int fhr = info.getFhr();
                            //   有些设备是没有宫缩，电量这些信息。。
                            // 宫缩
                            int toco = info.getToco();
                            // 电量
                            int bv = info.getRealDevicePower();
                            // 电量百分比
                            int powerPregress = info.getDevicePower();
                            Log.d(TAG, String.format("胎心:%s 宫缩：%s 电量:%s 电量百分比:%s", fhr, toco, bv, powerPregress));
//                            chartView.addData(fhr, toco);
                            chartView.addData(fhr);
                            xinlv.add(fhr);
                            tvTime.setText(mp3RecordTimeCreater.getTimeString());
                        }
                        Log.d(TAG, "耗时---》" + (System.currentTimeMillis() - startTime));
                    }
                });
            }
        });
        tvConnectedState = (TextView) findViewById(R.id.tx_4);
        td_4 = (TextView) findViewById(R.id.td_4);
        tvTime = (TextView) findViewById(R.id.sc_4);
        // 胎心记录图表
        mAdFetalHeartChart = (ADFetalHeartChart) findViewById(R.id.aDFetalHeartChart);
//        mAdFetalHeartChart.setRatio(2f,2f);
        //这个可以设置比例，胎心视图的  高度/ 宽度
//        mAdFetalHeartChart.setRatio(2f,2f);
        if (mAdFetalHeartChart != null) {
            //设置是否有宫缩 绘图区域
//            mAdFetalHeartChart.setHaveToco(mADFetalHeart.getMode() == Mode.BLUE);
            mAdFetalHeartChart.setHaveToco(false);
            // 得到一个真实的 胎心绘制View
            chartView = mAdFetalHeartChart.getLineView();
            // 设置 一屏显示多少分钟
//            chartView.setOneScreenMinute(6);
            //设置 视图开始滚动时间
//            chartView.setStartScrollTime(1);

            // 设置 滚动间隔，模认一分钟。
            //chartView.setIntervalTime(1);
        }
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        shu = (Button) findViewById(R.id.shu);
        qie_huan = (Button) findViewById(R.id.qie_huan);
        td_0 = (RelativeLayout) findViewById(R.id.td_0);
        tx_1 = (TextView) findViewById(R.id.tx_1);
        tx_2 = (TextView) findViewById(R.id.tx_2);
        // 准备
        mADFetalHeart.prepare();
        // 开始公做
        mADFetalHeart.startWork();
        mp3RecordTimeCreater.initTimer();
        // 记录结束的回调
        // 可以在这里进行一些数据库的存储或者网络上传相关
        mADFetalHeart.setFinishCallback(new FinishCallback() {
            @Override
            public void onFinish(String path) {
                Log.d(TAG, "path---->" + path);
            }
        });
        mADFetalHeart.setConnectCallback(new ConnectCallback() {
            @Override
            public void onConnectSuccess() {
            }

            @Override
            public void onConnectFail(boolean setting) {
                int mode = mADFetalHeart.getMode();
                String text = "蓝牙外设";
                if (mode == Mode.LINE) {
                    text = "有线外设";
                }
                //设备断开连接
                Snackbar.make(stop, String.format("%s已断开", text), Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                // 外设断开，这个时候需要停止记录
                stopClick();
            }
        });
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        qie_huan.setOnClickListener(this);
        shu.setOnClickListener(this);
    }

    protected void startClick() {
        if (moshi == 0) {
            start.setVisibility(View.GONE);
            stop.setVisibility(View.VISIBLE);
            shu.setVisibility(View.VISIBLE);
        } else {
            start.setVisibility(View.GONE);
            stop.setVisibility(View.VISIBLE);
            shu.setVisibility(View.GONE);
        }
        isstart = true;
        chartView.clean();
        // 设置胎心文件存取的图径
        mADFetalHeart.setFile(fileFolderPath, System.currentTimeMillis() + "");
        // 开始 记录胎心
        mADFetalHeart.startRecording();
        mp3RecordTimeCreater.restTimeCount();
    }

    AlertDialog baocun;
    TextView riqi;

    protected void stopClick() {
        isstart = false;
        // 停止记录 胎心
        mADFetalHeart.stopRecording();
        baocun = MyAlertDialog.ShowDialog(RecordingActivity.this, R.layout.dialog_baocun);
        riqi = (TextView) baocun.findViewById(R.id.ri_qi_xuan_ze);
        riqi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateDialog.showShiJianRiQi(RecordingActivity.this, (TextView) v);
            }
        });
        baocun.findViewById(R.id.qu_xiao_bao_cun).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baocun.dismiss();
            }
        });
        baocun.findViewById(R.id.que_ding_bao_cun).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baocun.dismiss();
                String shijian = riqi.getText().toString();
                if (!TextUtils.isEmpty(shijian)) {
                    baocun(shijian);
                } else {
                    ToastUtil.showToast(RecordingActivity.this, "日期不能为空");
                }

            }
        });
    }

    AlertDialog baocundialog;

    void baocun(final String shijian) {
        baocundialog = MyAlertDialog.ShowDialog(RecordingActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    XinLv xinLv=new XinLv();
                    xinLv.setRecordDate(shijian);
                    xinLv.setFhRs(xinlv);
                    if (moshi == 0) {
                        xinLv.setKeepScore(taidong);
                    }
                    xinLv.setMode(moshi);
                    xinLv.setRecordSeconds(tvTime.getText().toString());
                    /*
                    1）toJson() – 转换java对象到JSON
                    2) fromJson() – 转换JSON到java对象
                    */
                    String p=new Gson().toJson(xinLv);
                    Log.i(TAG, "param==="+p);
                    String tokens= Constants.getStringByName(RecordingActivity.this,"yonghu");
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> token = new Gson().fromJson(tokens, type1);
                    Log.i(TAG, "access_token==" + "Bearer "+token.get("access_token"));
                    //OkHttp设置post请求编码
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),p);
                    //OkHttp请求数据
                    Request request = new Request.Builder().url(APIMethod.TianJiaXinLv).addHeader("Authorization","Bearer "+token.get("access_token")).post(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    Log.i(TAG, "code==" + code);
                    Log.i(TAG, bodys+"66666666666666666666666666");
                    if (code == 204||code==200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1=code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mp3RecordTimeCreater.cancelTimer();
        // 停止工作
        mADFetalHeart.stopWork();
    }

    AlertDialog qiehuan;
    ImageView tai_er, cheng_ren;
    int dianji = 0;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                startClick();
                break;
            case R.id.stop:
                stopClick();
                break;
            case R.id.qie_huan:
                qiehuan = MyAlertDialog.ShowDialog(RecordingActivity.this, R.layout.dialog_qie_huan);
                tai_er = (ImageView) qiehuan.findViewById(R.id.tai_er);
                cheng_ren = (ImageView) qiehuan.findViewById(R.id.cheng_ren);
                ImageView qu_xiao = (ImageView) qiehuan.findViewById(R.id.qu_xiao);
                if (moshi == 0) {
                    tai_er.setImageResource(R.mipmap.img_0033);
                    cheng_ren.setImageResource(R.mipmap.img_0036);
                } else {
                    tai_er.setImageResource(R.mipmap.img_0035);
                    cheng_ren.setImageResource(R.mipmap.img_0034);
                }
                tai_er.setOnClickListener(onClickListener);
                cheng_ren.setOnClickListener(onClickListener);
                qu_xiao.setOnClickListener(onClickListener);
                break;
            case R.id.shu:
                String time = mp3RecordTimeCreater.getTimeString();
                String[] my = time.split(":");
                int min = Integer.parseInt(my[0]);
                int sec = Integer.parseInt(my[1]);
                int zong = min * 60 + sec;
                if (zong - dianji >=15) {
                    dianji = zong;
                    taidong++;
                    td_4.setText(taidong + "");
                } else {
                    ToastUtil.showToast(RecordingActivity.this, "15秒后再点击，请稍等！");
                }
                break;
        }
    }
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tai_er:
                    tai_er.setImageResource(R.mipmap.img_0033);
                    cheng_ren.setImageResource(R.mipmap.img_0036);
                    qie_huan.setText("胎儿模式");
                    moshi = 0;
                    td_0.setVisibility(View.VISIBLE);
                    tx_2.setText("正常参考范围 : 110-160");
                    break;
                case R.id.cheng_ren:
                    tai_er.setImageResource(R.mipmap.img_0035);
                    cheng_ren.setImageResource(R.mipmap.img_0034);
                    qie_huan.setText("成人模式");
                    moshi = 1;
                    td_0.setVisibility(View.GONE);
//                    tx_1.setText("心率");
                    tx_2.setText("");
                    break;
                case R.id.qu_xiao:
                    qiehuan.dismiss();
                    break;
            }
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    baocundialog.dismiss();
                    ToastUtil.showToast(RecordingActivity.this, "保存成功");
                    finish();
                    break;
                case 1:
                    baocundialog.dismiss();
                    if (400<=msg.arg1&&msg.arg1<500){
                        ToastUtil.showToast(RecordingActivity.this, "保存失败");
                    }else{
                        Type type = new TypeToken<HashMap<String, Object>>() {}.getType();
                        HashMap<String, Object> errmsg = new Gson().fromJson(msg.obj.toString(), type);
                        Type type1 = new TypeToken<HashMap<String, String>>() {}.getType();
                        HashMap<String, String> error=new Gson().fromJson(errmsg.get("error").toString(),type1);
                        ToastUtil.showToast(RecordingActivity.this, error.get("message"));
                    }
                    break;
            }
        }
    };
}
